"""
    qsiauth.strategies.testadmin
    ============================
    Admin portal for populating data
    run /auth/testadmin to create a test account for admin
"""
from __future__ import absolute_import
from qsiauth import models
from qsiauth.strategies.base import BaseStrategy
from webapp2_extras import security



class TestAdminStrategy(BaseStrategy):

    def create_profile(self, auth_id, user_info, **kwargs):
        """
        Overrides to provide logic for checking and encrypting  passwords.
        :param auth_id:
        :param user_info:
        :param kwargs:
        :return:
        :raise:
        """
        password = kwargs.pop('password')
        profile = models.UserProfile.get_by_id(auth_id)
        if profile:
            # Profile exists
            return self.raise_error('The email that you\'ve provided '
                                    'exists in our records. '
                                    'Please try again.')
        profile = models.UserProfile.get_or_create(auth_id, user_info,
                password=security.generate_password_hash(password, length=12))
        return profile

    def handle_request(self, req):
        # confirm that required fields are provided.
        password = 'info'
        user_info = {}
        user_info['password'] = password
        user_info['emails'] = [{'value': 'info@perationtech.com', 'type': 'home', 'primary': True}]
        auth_id = models.User.generate_auth_id('welcome', 'info@perationtech.com')
        user_info = {
            'auth_id': auth_id,
            'info': user_info,
            'extra': {
                'raw_info': user_info,
                }
        }
        profile = self.create_profile(
            auth_id=user_info['auth_id'],
            user_info=user_info,
            password=password)
        req.register_user_by_profile(profile)
#        req.load_user_by_profile(profile)
        return req.get_redirect_uri()
